package com.ktmall.ktmalluijava.service.impl;

import com.ktmall.ktmalluijava.mapper.CategoryMapper;
import com.ktmall.ktmalluijava.pojo.Category;
import com.ktmall.ktmalluijava.service.CategoryService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/5/14 上午10:19
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    /**
     * 根据分类名称获取分类列表
     *
     * @param name
     * @return
     */
    @Override
    public List<Category> getByName(String name) {
        //获取所有分类列表
        List<Category> allCategories = categoryMapper.getByName(name);

        //构建父节点快速查找表
        Map<Long, List<Category>> parentIdMap = allCategories.stream().
                collect(Collectors.groupingBy(Category::getParentId));

        if(name==null || name.isEmpty()){
            //如果name为null，直接返回所有一级分类
            return allCategories.stream().filter(c -> c.getParentId()==0).
                    map(root -> buildTree(root, parentIdMap)).collect(Collectors.toList());
        }
        //如果name不为null，返回所有分类
       return allCategories.stream().filter(c -> c.getParentId()>=0).
                map(child -> buildTree(child, parentIdMap)).toList();
    }

    /**
     * 递归构建分类树
     *
     * @param node
     * @param parentIdMap
     * @return
     */
    private Category buildTree(Category node, Map<Long, List<Category>> parentIdMap) {
        List<Category> children = parentIdMap.getOrDefault(node.getId(), Collections.emptyList());
        children.forEach(child -> buildTree(child, parentIdMap));
        node.setChildren(children);
        return node;
    }


    /**
     * 删除分类
     *
     * @param id
     * @return
     */
    @Override
    public int delete(Integer id) {
        return categoryMapper.delete(id);
    }

    /**
     * 添加分类
     *
     * @param category
     * @return
     */
    @Override
    public int add(Category category) {
        return categoryMapper.add(category);
    }

    /**
     * 查询分类详情
     *
     * @param id
     * @return
     */
    @Override
    public Category detail(Integer id) {
        return categoryMapper.detail(id);
    }

    /**
     * 根据分类等级获取分类列表
     *
     * @param categoryLevel
     * @return
     */
    @Override
    public List<Category> getByCategoryLevel(Integer categoryLevel) {
        return categoryMapper.getByCategoryLevel(categoryLevel);
    }

    /**
     * 获取分类的层数
     *
     * @return
     */
    @Override
    public int count() {
        return categoryMapper.count();
    }

    /**
     * 更新分类详情
     *
     * @param category
     * @return
     */
    @Override
    public int update(Category category) {
        return categoryMapper.update(category);
    }


}
